# -*- coding: utf-8 -*-
import os
from logger import init  # noqa 加载logger设置
import time
from dir_op import get_dict, get_ip_method
import configparser
from file_op import mv_target
from snmptrap_op import send_msg, send_listening_msg
import logging
import schedule

init()
config = configparser.ConfigParser()
config.read('config')

log = logging.getLogger(__name__)

last_sended_map = {}

SENDED_MAP_QUEUE_KEY = "{ip}-{action}-{nums}"


def main():
    source_path = config['init']['source_path']
    target_path = config['init']['target_path']
    per_time = int(config['init']['per_time'])
    send_trigger_nums = int(config['init']['send_trigger_nums'])
    window_time = int(config['init']['window_time'])
    snmptrap_time_interval = int(config['init'].get('snmptrap_time_interval', 15*60))

    snmptrap_host = config['snmptrap']['host']
    snmptrap_port = int(config['snmptrap']['port'])

    dic_data = get_dict(source_path, per_time, send_trigger_nums, window_time=window_time)
    log.debug(dic_data)
    for _, idx_dic in dic_data.items():
        for _, files in idx_dic.items():
            ip, nums, tm, action = get_ip_method(files[0])
            key = SENDED_MAP_QUEUE_KEY.format(ip=ip, nums=nums, action=action)
            now = int(time.time())
            if key not in last_sended_map:
                last_sended_map[key] = now
            if ((last_sended_map[key] == now) or (now - last_sended_map[key]) >= snmptrap_time_interval):
                # 初始化或者当前时间减去最后一次发送时间大于等于设定时间时发送
                send_msg(snmptrap_host, snmptrap_port, ip, action, tm[:-3], [os.path.basename(item) for item in files])
                last_sended_map[key] = now - 1

            for file in files:
                mv_target(file, source_path, target_path)

    log.info("Starting")


if __name__ == '__main__':
    event_loop = int(config['init'].get('event_loop', 15))
    listening_loop_time = int(config['init'].get('listening_loop_time'))

    snmptrap_host = config['snmptrap']['host']
    snmptrap_port = int(config['snmptrap']['port'])

    schedule.every(event_loop).seconds.do(main)
    schedule.every(listening_loop_time).seconds.do(send_listening_msg, snmptrap_host, snmptrap_port)

    while True:
        try:
            schedule.run_pending()
        except IOError as e:
            log.warning("retry error" + str(e))
        except Exception as e:
            log.error(e)
        time.sleep(1)
